package
{
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.text.Font;
	import flash.utils.Timer;
	
	public class SnakeGame extends Sprite
	{
		/**
		 * 蛇头 
		 */
		private var head:Head;
		/**
		 * 计时器 
		 */
		private var timer:Timer;
		/**
		 * 蛇身数组 
		 */		
		private var partArr:Array = [];
		
		private var foodArr:Array = [];
		public function SnakeGame()
		{
			init();
		}
		
		/**
		 * 
		 * 
		 */
		private function init():void
		{
			// 初始化蛇头
			head = new Head();
			this.addChild( head );
			
			/*addPart();
			addPart();
			addPart();*/
			
			addFood();
			
			// 启动计时器
			timer = new Timer(100);
			timer.addEventListener(TimerEvent.TIMER, update);
			timer.start();
		}
		/**
		 * 添加食物 
		 * 
		 */		
		private function addFood():void
		{
			var food:Food = new Food();
			this.addChild( food );
			// 用递归函数获取随机位置
			var p:Point = getFoodPosition();
			food.x = p.x;
			food.y = p.y;
			
			foodArr.push( food );
		}
		/**
		 *  获取随机位置
		 * @return 
		 * 
		 */		
		private function getFoodPosition():Point
		{
			var _x:int = int( Math.random() * 30 ) * 12;
			var _y:int = int( Math.random() * 20 ) * 12;
			for(var i:int=0; i<partArr.length; i++)
			{
				var part:Part = partArr[i];
				if( _x == part.x && _y == part.y )
				{
					return getFoodPosition();
				}
			}
						
			return new Point(_x, _y);
		}
		/**
		 * 添加身体 
		 * 
		 */		
		private function addPart():void
		{
			var part:Part = new Part();
			
			// 添加身体的时候，如果有身体，则添加到最后一截的位置
			if( partArr.length > 0 )
			{
				part.x = partArr[partArr.length-1].x;
				part.y = partArr[partArr.length-1].y;
			}else // 如果没有身体，则添加到蛇头的位置
			{
				part.x = head.x;
				part.y = head.y;
				// 将蛇头放到最前面，不然会被蛇身挡住
				this.setChildIndex( head, this.numChildren - 1 );
			}
			
			this.addChild( part );
			partArr.push( part );
		}
		/**
		 * 
		 * @param event
		 * 
		 */		
		protected function update(event:TimerEvent):void
		{
			var i:int;
			// 更新蛇头位置
			head.update();
			// 更新蛇身位置
			for (i = 0; i < partArr.length; i++) 
			{
				var part:Part = partArr[i];
				part.lastPoint = new Point( part.x, part.y );
				if( i == 0 ) // 第一节身子跟随蛇头运动
				{
					part.x = head.lastPoint.x;
					part.y = head.lastPoint.y;
				}else// 后面的身子跟随前面一节
				{
					part.x = partArr[i-1].lastPoint.x;
					part.y = partArr[i-1].lastPoint.y;
				}
			}
			// 检测蛇头有没有吃到食物
			for( i = foodArr.length - 1; i>=0; i--)
			{
				var food:Food = foodArr[i];
				if( head.hitTestObject( food ) )
				{
					// 从食物数组中删除
					foodArr.splice( i,1);
					// 移除食物
					this.removeChild( food );
					// 添加一截身子
					addPart();
					// 添加一个食物
					addFood();
										
				}
			}
		}
	}
}